package com.zn.opit.miniodemo.controller;

import com.zn.opit.miniodemo.domain.R;
import com.zn.opit.miniodemo.domain.param.GetMinioUploadInfoParam;
import com.zn.opit.miniodemo.domain.param.MergeMinioMultipartParam;
import com.zn.opit.miniodemo.domain.minio.MinioUploadInfo;
import com.zn.opit.miniodemo.exception.MinioDemoException;
import com.zn.opit.miniodemo.exception.MinioDemoExceptionTypes;
import com.zn.opit.miniodemo.service.FileUploadService;
import org.apache.commons.lang3.StringUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RequestMapping("/slicefile")
@RestController
public class SliceUploadController {

    @Resource
    private FileUploadService fileUploadService;

    @PostMapping("/upload")
    public R getUploadId(@Validate @RequestBody GetMinioUploadInfoParam param) {
        MinioUploadInfo minioUploadId = fileUploadService.getUploadId(param);
        return R.ok().setData(minioUploadId);
    }

    @GetMapping("/upload/check")
    public R checkFileUploadedByMd5(@RequestParam("md5") String md5) {
        return R.ok().setData(fileUploadService.checkFileExistsByMd5(md5));
    }

    @PostMapping("/upload/merge")
    public R mergeUploadFile(@Validated MergeMinioMultipartParam param) {
        String result = fileUploadService.mergeMultipartUpload(param);
        if (StringUtils.isEmpty(result)) {
            throw new MinioDemoException(MinioDemoExceptionTypes.CHUNK_MERGE_FAILED);
        }
        return R.ok().setData(result); // url
    }
}
